package com.stormrage.edu.ctrl.edu;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduChapterServ;
import com.stormrage.edu.serv.edu.EduCourseServ;
import com.stormrage.edu.serv.edu.EduLecServ;
import com.stormrage.edu.serv.edu.view.EduCourseChapterServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduCourse;
import com.stormrage.entity.edu.EduLec;
import com.stormrage.entity.edu.rep.EduChapterRep;
import com.stormrage.entity.edu.req.EduChapterReq;
import com.stormrage.entity.edu.req.EduCourseReq;
import com.stormrage.entity.edu.view.EduCourseChapter;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @Title: EduCourseCtrl.java
 * @Package com.stormrage.edu.ctrl
 * @Description: 课程 Controller
 * @author www.stormragetech.com
 * @date 2016年4月10日
 * @version V1.0
 */
@Controller
@RequestMapping("/course")
public class EduCourseCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduCourseCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduChapterServ eduChapterServ;

	@Autowired
	private EduCourseChapterServ eduCourseChapterServ;

	@Autowired
	private EduCourseServ eduCourseServ;

	@Autowired
	private EduLecServ eduLecServ;

	@RequiresPermissions("course:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			List<EduLec> array = eduLecServ.queryList();

			if (null == array || array.size() <= 0) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "还未添加教师，请先添加讲师",
						StormrageTechException.ERR_APP, "【 EduCourseCtrl 】-【 Create 】");

				err = ErrorRep.instance(false, exception.getMessage());
				model.addAttribute("err", err);

				return "edu/course/create";

			}

			model.addAttribute("lecs", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "edu/course/create";

	}

	@RequiresPermissions("course:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduCourse entity, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {
			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "您没有上传课程图片",
					StormrageTechException.ERR_APP, "【 EduCourseCtrl 】-【 Create 】");
			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);
			return "redirect:/edu/course/create";
		}

		try {

			String path = rootPath + imagePath;
			String fileName = eduCourseServ.upload(file, path);
			entity.setImage(fileName);

			// ------------------ Ctrl操作 ------------------

			eduCourseServ.create(entity);
			errMsg = "提示信息：添加课程成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加课程失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/course/list";

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduCourse entity = eduCourseServ.queryById(id);
			model.addAttribute("data", entity);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			List<EduLec> array = eduLecServ.queryList();

			if (null == array || array.size() <= 0) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "还未添加教师，请先添加讲师",
						StormrageTechException.ERR_APP, "【 EduCourseCtrl 】-【 Edit 】");

				err = ErrorRep.instance(false, exception.getMessage());
				model.addAttribute("err", err);

				return "edu/course/create";

			}

			model.addAttribute("lecs", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/course/edit";

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, EduCourse req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			eduCourseServ.update(req);
			errMsg = "提示信息：修改课程成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改课程失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/course/list";

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/upload/{id}", method = RequestMethod.GET)
	public String upload(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 upload 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 upload 】-【 GET 】- 结束运行 ");
		return "edu/course/upload";

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST)
	public String upload(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 upload 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file || file.isEmpty()) {
			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "您没有上传课程图片",
					StormrageTechException.ERR_APP, "【 EduCourseCtrl 】-【 upload 】");
			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);
			return "redirect:/edu/course/upload";
		}

		try {

			String path = rootPath + imagePath;
			String fileName = eduCourseServ.upload(file, path);

			EduCourse entity = eduCourseServ.queryById(id);
			entity.setImage(fileName);

			// ------------------ Ctrl操作 ------------------

			eduCourseServ.update(entity);
			errMsg = "提示信息：修改课程图片成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改课程图片失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 upload 】-【 POST 】- 结束运行 ");
		return "redirect:/course/list";

	}

	@RequiresPermissions("course:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduCourseServ.delete(id);
			errMsg = "提示信息：删除课程成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除课程失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/course/list";

	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EduCourseReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "edu/course/list";
	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduCourseReq req) {

		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduCourseServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	/// -------------------------------------------------- ///
	/// ------------------ 已包含章节列表 ------------------ ///
	/// -------------------------------------------------- ///
	@RequiresPermissions("course:view")
	@RequestMapping(value = "/list/{id}")
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Add 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EduChapterRep> array = eduChapterServ.queryRepListById(id);
			if (null != array && array.size() > 0)
				model.addAttribute("data", array);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", array);
			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "edu/course/chap/list";
	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/chap/del/{cid}/{id}")
	public String deleteView(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid,
			@PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 DeleteView 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 判断是否允许删除章节 ------------------
			EduCourse course = eduCourseServ.queryById(cid);
			if (course.getChap().equals(0)) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR,
						"提示信息：编号为【 " + id + " 】的课程只包含唯一章节，不能删除此章节", StormrageTechException.ERR_APP,
						"【 EduCourseCtrl 】-【 DeleteView 】");

				err = ErrorRep.instance(false, exception.getMessage());
				redirect.addFlashAttribute("err", err);

				return "redirect:/course/list/{id}";

			}

			// ------------------ Ctrl操作 ------------------
			eduCourseChapterServ.deleteById(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的课程章节关联成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除【 " + id + " 】的课程章节关联失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/list/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 DeleteView 】-【 GET 】- 结束运行 ");
		return "redirect:/course/list/{cid}";

	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/chap/add/{id}")
	public String list(@CurrentUser ShiroAcct curr, EduChapterReq req, @PathVariable("id") Integer id, Model model,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 List Chap Except 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);
			model.addAttribute("id", id);

			// ------------------ 判断是否允许添加章节 ------------------
			EduCourse course = eduCourseServ.queryById(id);
			if (course.getChap().equals(0)) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR,
						"提示信息：编号为【 " + id + " 】的课程只包含唯一章节，不能增加其他章节", StormrageTechException.ERR_APP,
						"【 EduCourseCtrl 】-【 DeleteView 】");

				err = ErrorRep.instance(false, exception.getMessage());
				redirect.addFlashAttribute("err", err);
				return "redirect:/course/list/{id}";
			}

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 List Chap Except 】-【 GET 】- 结束运行 ");
		return "edu/course/chap/add";

	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/chap/ajax/{id}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			EduChapterReq req) {

		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax Chap 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduChapterServ.queryList(id, req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax Chap 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/chap/add/{cid}/{id}")
	public String add(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid, @PathVariable("id") Integer id,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Add 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			EduCourseChapter entity = EduCourseChapter.instance(cid, id);
			eduCourseChapterServ.create(entity);

			errMsg = "提示信息：关联章节成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：关联章节失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/course/chap/add/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "redirect:/course/chap/add/{cid}";

	}

}
